<template>
  <div class="about">
    <h1>{{ id ? '编辑': '新建' }}物品</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="名称">
        <el-input v-model="model.name" ></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="model.icon" :src="model.icon" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item> 
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {
    // 这个id是拿到路由里编辑的id
    id: {}
  },
  data(){
    return {
      model: {},
    }
  },
  methods: {
    // 图片上传成功函数
    handleAvatarSuccess(res) {
      // 因为vue 双向绑定初始值问题 所以做好用 $set()
      // this.model.icon = res.url
      this.$set(this.model, 'icon', res.url)
    },
    beforeAvatarUpload(res) {
      
    },
    // 新建和编辑因为是同一个页面，所以还需要条件判断请求不同
    async save(){
      let res
      if(this.id){
        res = await this.$http.put(`rest/items/${this.id}`, this.model)
      } else {
        res = await this.$http.post('rest/items', this.model) 
      }
      this.$router.push('/items/list')
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    async fetch() {
      const res = await this.$http.get(`/rest/items/${this.id}`)
      this.model = res.data
    },
  },
  created() {
    // 如果能拿到编辑的id 才会请求接口，将分类名称展示到页面上
    this.id && this.fetch()
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>

